package com.ft.adbix.utils.download;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.ft.adbix.utils.AdLogUtils;
import com.ft.adbix.utils.permission.PermissionUtils;
import com.ft.adbix.utils.download.receiver.DownloadReceiver;

import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class DownloadUtils {

    private Map<String, Long> downloadQueue = new HashMap<>();
    private Context context;

    private DownloadManager downloadManager;
    private DownloadReceiver receiver;

    private static final class InstanceHolder {
        static final DownloadUtils instance = new DownloadUtils();
    }

    public static DownloadUtils getInstance() {
        return InstanceHolder.instance;
    }

    private DownloadUtils() {
    }

    @SuppressLint("WrongConstant")
    public void init(Context context) {
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        receiver = new DownloadReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        filter.addAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 34) {
            context.registerReceiver(receiver, filter, 4);
        } else {
            context.registerReceiver(receiver, filter);
        }
        this.context = context;
    }

    public void downloadApk(String url, String title) {
        if (!getNetworkState()) {
            Toast.makeText(context, "网络状况不佳", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!PermissionUtils.hasExternalPermission()){
            Toast.makeText(context, "需要获取读取文件权限", Toast.LENGTH_SHORT).show();
            return;
        }
        if (downloadQueue.containsKey(url)) {
            Toast.makeText(context, "已在下载列表", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "开始下载", Toast.LENGTH_SHORT).show();
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "target.apk");
            request.setTitle(title);
            request.setVisibleInDownloadsUi(false);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            long downloadId = downloadManager.enqueue(request);
            downloadQueue.put(url, downloadId);
        }
    }

    /**
     * 获取网络状态
     *
     * @return true连接 false未连接
     */
    private boolean getNetworkState() {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null;
    }

    public boolean checkSelfDownloadId(long downloadId) {
        for (String key : downloadQueue.keySet()) {
            Long saveId = downloadQueue.get(key);
            if (saveId != null && saveId == downloadId) {
                return true;
            }
        }
        return false;
    }

    public void removeDownloadId(long downloadId) {
        for (String key : downloadQueue.keySet()) {
            Long saveId = downloadQueue.get(key);
            if (saveId != null && saveId == downloadId) {
                downloadQueue.remove(key);
                downloadManager.remove(downloadId);
            }
        }
    }

    public void checkDownloadComplete(long downloadId) {
        if (checkSelfDownloadId(downloadId)) {
            //获取Query
            DownloadManager.Query query = new DownloadManager.Query();
            //根据下载ID过滤
            query.setFilterById(downloadId);
            //根据下载状态过滤
//            query.setFilterByStatus(DownloadManager.STATUS_RUNNING);
            //查询-Cursor的使用方法与SQLite一致
            Cursor cursor = downloadManager.query(query);
            AdLogUtils.d("下载状态：" + cursor.getCount());
            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int failedReasonIndex = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
            int filePath = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
            if (cursor.moveToNext()) {
                int status = cursor.getInt(columnIndex);
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    String uri = cursor.getString(filePath);
                    AdLogUtils.d("下载完成：" + uri);
                    installApk(uri);
                    removeDownloadId(downloadId);
                } else if (status == DownloadManager.STATUS_FAILED) {
                    AdLogUtils.d("下载失败：" + cursor.getInt(failedReasonIndex));
                    removeDownloadId(downloadId);
                }
            }

        }
    }

    public void installApk(String uriStr) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".adbix.fileprovider", new File(URI.create(uriStr)));
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            AdLogUtils.d("安装失败");
            e.printStackTrace();
        }
    }

}
